extends ColorRect

@onready var itemRoot = $ItemRoot
@export var horizontalMaxCount = 7
@export var itemSize = 16
@export var scrollStrenth = 5

var inventory 
var needScroll = false
var scrollMinPosY
var scrollMaxPosY


func _ready():
	inventory = get_parent()
	initItems()
	

func _physics_process(delta):
	processScroll(delta)
	
		
func processScroll(delta):
	if not inventory.enableInput or not needScroll: return
	
	if Input.is_action_just_pressed("MouseWheelUp"):
		scrollItem(scrollStrenth)
		
	if Input.is_action_just_pressed("MouseWheelDown"):
		scrollItem(-scrollStrenth)
		

func scrollItem(strenth):
	var tentativeY = itemRoot.position.y + strenth
	tentativeY = clamp(tentativeY, scrollMinPosY, scrollMaxPosY)
	itemRoot.position.y = tentativeY
	

func initItems():
	Global.clearChildNode(itemRoot)
	
	var itemsData = null
	itemsData = getItemDatasByItemType(Inventory.currentItemTypeTab)
	
	if not itemsData: return
	
	var count = itemsData.size()
	var targetPosition = Vector2.ZERO
	var lineCount = ceil(count * 1.0 / horizontalMaxCount) 
	var totalHeight = itemSize * lineCount + lineCount - 1 
	
	itemRoot.size.y = totalHeight
	
	scrollMinPosY = size.y - totalHeight
	scrollMaxPosY = 0
	
	for i in range(itemsData.size()):
		var itemData = itemsData[i]
		var itemNode:Control = Global.createSceneInst(Consts.RESOURCE_UI_ITEM)
		itemRoot.add_child(itemNode)
		itemNode.initItem(itemData, Inventory.currentItemTypeTab)
		
		targetPosition.x = (i % horizontalMaxCount) * (itemSize + 1)
		targetPosition.y = floor(i / horizontalMaxCount) * (itemSize + 1)
		itemNode.position = targetPosition
	
	needScroll = totalHeight > size.y
	
	itemRoot.position.y = 0
		

func getItemDatasByItemType(itemType):
	var result = null
	
	if itemType == Consts.ITEM_TYPE_WEAPON:
		result = GlobalData.weaponsData
	elif itemType == Consts.ITEM_TYPE_EQUIPMENT:
		result = GlobalData.equipmentsData
	elif itemType == Consts.ITEM_TYPE_CONSUMABLE:
		result = GlobalData.itemsData
		
	return result
		
		
		

